<script>
	export default {
		onLaunch: function(options) {
			let qrcode = '';
			if(options.query.qrcode){
				qrcode = options.query.qrcode
				uni.setStorageSync('qrcode',qrcode)
			}
			const VConsole = require('@/static/js/vconsole.min.js');
			new VConsole()
			console.log('App Launch')
			// uni.setStorageSync('openid','o5Tpz6QFUmFIJxRLPixK9GxEM8CI')
			// uni.setStorageSync('openid','o5Tpz6Yu1PUFghHsXOgBDpcNYdec')
			let openid = uni.getStorageSync('openid')
			if(openid){
				this.post('user/login',{
					open_id:openid
				}).then(res=>{
					uni.setStorageSync('userInfo',res.data.userinfo)
					uni.setStorageSync('token',res.data.userinfo.token)
				}).catch(res=>{
					this.post('user/register',{
						open_id:openid,
						nickname:uni.getStorageSync('nickname'),
						avatar:uni.getStorageSync('avatar'),
						code:qrcode
					}).then(res=>{
						uni.setStorageSync('userInfo',res.data.userinfo)
						uni.setStorageSync('token',res.data.userinfo.token)
					})
				})
			}else{
				if(this.queryURLParams('code')){
					console.log(this.queryURLParams('code'))
					this.get('user/callback',{
						code:this.queryURLParams('code')
					}).then(res=>{
						console.log(res)
						let openid = res.data.open_id
						uni.setStorageSync('openid',openid)
						uni.setStorageSync('nickname',res.data.nickname)
						uni.setStorageSync('avatar',res.data.avatar)
						this.post('user/login',{
							open_id:openid
						}).then(res=>{
							uni.setStorageSync('userInfo',res.data.userinfo)
							uni.setStorageSync('token',res.data.userinfo.token)
						}).catch(res=>{
							this.post('user/register',{
								open_id:openid,
								nickname:uni.getStorageSync('nickname'),
								avatar:uni.getStorageSync('avatar'),
								code:qrcode
							}).then(res=>{
								uni.setStorageSync('userInfo',res.data.userinfo)
								uni.setStorageSync('token',res.data.userinfo.token)
							})
						})
					}).catch(res=>{
						console.log(res)
					})
				}else{
					let appid = 'wx3d755d9e7a1e4ceb'
					let uri = window.location.href.split('?code')[0]
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid +
						'&redirect_uri=' + encodeURIComponent(uri) +
						'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
				}
			}
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods:{
			queryURLParams(type) {
				let url = window.location.href
			    let pattern = /(\w+)=(\w+)/ig; //定义正则表达式
			    let parames = {}; // 定义参数对象
			    url.replace(pattern, ($, $1, $2) => {
			      parames[$1] = $2;
			    });
			    return parames?parames[type]:null;
			},
		}
	}
</script>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>
